B07GL978YK EBOK by Bruno Skvorc & Ahmed Bouchefra & Mislav Javor & Tonino Jankov

B07GL978YK EBOK by Bruno Skvorc & Ahmed Bouchefra & Mislav Javor & Tonino Jankov

Author:Bruno Skvorc & Ahmed Bouchefra & Mislav Javor & Tonino Jankov [Skvorc, Bruno]
Language: eng
Format: epub
Published: 0101-01-01T00:00:00+00:00


JavaScript Testing

Truffle enables us to use JavaScript for testing, leveraging the Mocha testing framework. This enables you to write more complex tests and get more functionality out of your testing framework.

Okay, let’s write the test. First, in the test folder, create a file and call it hashmarket.js.

The first thing we need to do, is get the reference to our contract in JavaScript. For that, we’ll use Truffle’s artifacts.require(...) function:

var HashMarket = artifacts.require("./HashMarket.sol");

Now that we have the reference to the contract, let’s start writing tests. To start, we’ll use the contract function provided to us:

contract("HashMarket", function(accounts) { });

This creates a test suite for our contract. Now for testing, we use Mocha it syntax:

contract("HashMarket", function(accounts) { it("should add a new product", function() { }); });

This describes the test we’ll write and presents a message for us to know the purpose of the test. Now let’s write the test itself. At the end, the hashmarket.js file should look like the following. The reasoning is explained in the comments of the source code:

var HashMarket = artifacts.require("./HashMarket.sol"); contract("HashMarket", function(accounts) { it("should add a new product", function() { // Set the names of test data var itemName = "TestItem"; var itemPrice = 1000; var itemSeller = accounts[0]; // Since all of our testing functions are async, we store the // contract instance at a higher level to enable access from // all functions var hashMarketContract; // Item ID will be provided asynchronously so we extract it var itemID; return HashMarket.deployed().then(function(instance) { // set contract instance into a variable hashMarketContract = instance; // Subscribe to a Solidity event instance.ItemAdded({}).watch((error, result) => { if (error) { console.log(error); } // Once the event is triggered, store the result in the // external variable itemID = result.args.itemID; }); // Call the addNewItem function and return the promise return instance.addNewItem(itemName, itemPrice, {from: itemSeller}); }).then(function() { // This function is triggered after the addNewItem call transaction // has been mined. Now call the getItem function with the itemID // we received from the event return hashMarketContract.getItem.call(itemID); }).then(function(result) { // The result of getItem is a tuple, we can deconstruct it // to variables like this var [name, price, seller, status] = result; // Start testing. Use web3.toAscii() to convert the result of // the smart contract from Solidity bytecode to ASCII. After that // use the .replace() to pad the excess bytes from bytes32 assert.equal(itemName, web3.toAscii(name).replace(//g, ''), "Name wasn't properly added"); // Use assert.equal() to check all the variables assert.equal(itemPrice, price, "Price wasn't properly added"); assert.equal(itemSeller, seller, "Seller wasn't properly added"); assert.equal(status, 0, "Status wasn't properly added"); }); }); });

Run truffle test and you should get something like this:

TestHashMarket ✓ testAddingNewProduct (109ms) Contract: HashMarket ✓ should add a new product (64ms) 2 passing (876ms)

Your test has passed and you can be confident about not having regression bugs.

For homework, write tests for all other functions in the contract.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(203334)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(171904)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(80321)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(79897)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(79664)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74426)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50881)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40254)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40212)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40087)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32725)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32503)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32450)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32381)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32357)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32329)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32253)
What's Done in Darkness by Kayla Perrin(27139)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26515)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26452)